<?php
/*
# ------------------------------------------------------------------------
# JA Job Board Package
# ------------------------------------------------------------------------
# Copyright (C) 2004-2010 JoomlArt.com. All Rights Reserved.
# @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
# Author: JoomlArt.com
# Websites: http://www.joomlart.com - http://www.joomlancers.com.
# ------------------------------------------------------------------------
*/

class JobBoardControllerJAJobs extends JobBoardController{

    /**
     * Constructor
     */
    function __construct( $default = array() )
    {
    	$layout = JRequest::getVar('layout');        
        parent::__construct( $default );
        $this->set('name', 'jobs');
        $this->set('fullname', 'jajobs');
        
        // Register Extra tasks
        $this->registerTask( 'add',        'edit' );
        $this->registerTask( 'adminadd',        'adminedit' );
        $this->registerTask( 'non-approved',        'approved' );
        $this->registerTask( 'apply',    'save' );
        $this->registerTask( 'inactivate',    'activate' );
    }
    
    function download(){
    	 $model    =& $this->getModel( 'jajobs' );    
         $model->download();
         exit;  
    }
    
    /**
    * Display current configuration of the component to administrator
    * 
    */
    function display(){
		JRequest::setVar('view', $this->get('fullname')); // Force using associated view
		$document = &JFactory::getDocument();

		$layout = JRequest::getVar('layout', 'jalist');
		$user = JFactory::getUser();
        if (($user->id==0&&$layout=='jaform')||($user->id==0&&$layout=='japremiumform'))
        {
            $uri = JFactory::getURI();
            $url = $uri->toString();
            $url = base64_encode($url);
        	$this->setRedirect(JRoute::_("index.php?option=com_user&view=login&return=".$url));        	
        	return ;
        }
		if ($layout=='done_new'||$layout=='done_update')
		{
			$this->done($layout);
			return ;
		}
        $user = &JFactory::getUser();
        
        // Make sure you are logged in and have the necessary access rights
        if (($layout=='employerjalist' && getCurrentUserType() != JBEMPLOYER_USER)&&($layout=='jobseekerjalist' && getCurrentUserType() != JBJOB_SEEKER_USER)) {
            JResponse::setHeader('HTTP/1.0 403',true);
            JError::raiseWarning( 403, JText::_("Access denied. You don't have permission.") ); 
            echo "<a href='javascript:window.history.go(-1);'>". JText::_('Back')."</a>"; 
            return;
        }
		parent::display();
    }
    
    /**
    * Cancel current operation
    * 
    */
    function cancel(){
        $Itemid = JRequest::getVar('Itemid');
        $this->setRedirect(JRoute::_("index.php?option=". JBCOMNAME ."&view=". $this->get('fullname')."&Itemid=".$Itemid));
    }
    
    /**
    * Remove a configuration row
    * 
    */
    function remove(){
    	// Check for request forgeries
    	
        $task = JRequest::getVar('task', 'remove');
        $model =& $this->getModel(JBPREFIX.'jobs');
               
        $n = $model->remove($task);
		
        $limited = JRequest::getVar('limited', 0);
        		
		$this->setMessage(JText::sprintf('Items removed', $n));
		$this->setRedirect(JRoute::_('index.php?option='. JBCOMNAME .'&view=jajobs&layout=myjobs'), JText::_('This job has removed'));
	}
	
	/*function activate(){
    	// Check for request forgeries
		JRequest::checkToken() or jexit( 'Invalid Token' );

        $Itemid = JRequest::getVar('Itemid');
        $limited = JRequest::getVar('limited');
        $model =& $this->getModel($this->get('fullname'));
        $task = JRequest::getVar('task', 'approved');
        $model->activate($task);
		$this->setRedirect('index.php?option='. JBCOMNAME .'&view='.$this->get('fullname').'&limited='.$limited.'&Itemid='.$Itemid);
	}*/
    
    /**
    * Edit forms
    */
    function edit($postback = false){
    	JRequest::setVar('edit', true);
        if ($postback)
        {
        	if (JRequest::getVar('layout')!='duplicate')
        	{
	        	if (JRequest::getVar('is_hotjob')==1)
			        JRequest::setVar('layout','japremiumform');
			     else 
			     	JRequest::setVar('layout','jaform');
        	}
        }
        parent::display();
    }
    
    function adminedit($postback = false)
    {
        JRequest::setVar('edit', true);
        $model = & $this->getModel($this->get('fullname'));
        $model->checkout();
        
        $view = & $this->getView($this->get('fullname'), 'html');
        $view->setModel($model, true);
        $view->setLayout('adminform');
        
        $view->adminedit($postback);    	
    }
    
    /**
    * View forms
    */
    /*function view(){
        JRequest::setVar('view', true);
        $model = & $this->getModel($this->get('fullname'));
//        $model->increaseViews();
//        $model->Set_LatestJob_View();
        $applicationmodel = $this->getModel(JBPREFIX.'applications');
        
        $view = & $this->getView($this->get('fullname'), 'html');
        $view->setModel($model, true);
        $view->setModel($applicationmodel);
		$view->setLayout(JBPREFIX."view");
        $view->view();
    }*/
	
    function processPaypal($paytype,$amount){
        require_once(JPATH_COMPONENT.DS."models".DS."jatransaction.php");
        //$pClass=new Paypal($jbconfig);
        $rowItem->item_name = $paytype;        
        $rowItem->amount = $amount;
        $user = &JFactory::getUser();
        $rowItem->userId = $user->id;
        $pClass = $this->getModel(JBPREFIX.'Paypal');
        $pClass->processPayment1($rowItem);
    }
    
    function save_application()
    {
    	require_once(JPATH_COMPONENT.DS."models".DS."jaapplications.php");
    	$model_app = new JobBoardModelJAApplications();
    	$result = $model_app->store();
    	if ($result)
    	{
    		$result = explode('_',$result);
    		setcookie('save_applicaton','success');
    		echo '<span style="color: blue; font-style: italic; font-weight: bold;" >'.JText::_('You have successfully applied for this job').'</span>';
//    		$msg = JText::_( 'You have successfully applied for this job' ); 
//    		$this->setRedirect( JRoute::_('index.php?option='. JBCOMNAME .'&view=jajobs&layout=jaview&cid[]='.$result[0].'&Itemid='.$Itemid), $result[1] );
    	}
    	else 
    	{
    		setcookie('save_applicaton','unsuccess');
    		$_COOKIE['save_applicaton'] = 'unsuccess';
//    		$post    = JRequest::get('request', JREQUEST_ALLOWHTML);
//    		JRequest::setVar('app_postback',true);
//    		JRequest::setVar('apply_data',$post);
//    		$cid = JRequest::getVar('job_id');
//    		JRequest::setVar('cid',$cid);
//    		JRequest::setVar('layout','jaview');
//    		
//    		parent::display();
    	}
    	exit;
    }
    
    function done($task)
    {
    	global $jbconfig;
    	$model    =& $this->getModel('jajobs');
    	$item	  = $model->getItem();
    	if ($task=='done_new')
    	{
    		if ($jbconfig['posts']->get('first_posting_status')=='Approved')
    			$msg = JText::_( 'Successfully posted job' );   
    		else {
    			$msg = JText::_( 'Successfully posted job, please wait for admin approval before your job is listed on job board' );
    			$model->mailEmployerNonApprovedJob($item->id, $item->user_id, $email_template = 'JobMailNonApproved');
    		}
    	}
    	else 
    	{
    		$msg = JText::_( 'Successfully updated job' );  
    		JRequest::setVar('layout','myjobs');
    		$this->setMessage($msg);
    		JError::raiseWarning(0, $msg);    		
    		$model->mailEmployerUpdatedJob($item->id, $item->user_id, $email_template = 'sendmail_to_employer_update_job');
    		parent::display();
    		return;
    	}
    	
        $this->setRedirect( JRoute::_('index.php?option='. JBCOMNAME .'&view=jajobs&layout=myjobs'), $msg );
    }
    
	/**
	* Save configuration record
	*/
	function save(){
		global $jbconfig, $option,$mainframe;				
		
		$user = &JFactory::getUser(); 
		$premium = JRequest::getInt('is_hotjob', 0);
		
		if(!$premium)	checkPermission('standard_post_job');
  		else checkPermission('premium_post_job');
  		
  		$model    =& $this->getModel('jajobs');
  		
  		$post = JRequest::get ( 'request', JREQUEST_ALLOWRAW );
		
		$model->setState('request', $post);
  		
  		$temp = $this->getModel('jajobs');
  		$item = $temp->getItem();
            
        if(!$premium && !$item->id && $jbconfig['billing']->get('posting_fee_enabled', 0)>0){
        	        
        	$account = getAccountByUserID($user->id);
        	if(!$account || (int)$account->standard_posts_balance<1){
        		$this->setRedirect("?option=$option&view=jajobs&layout=jaform&goto_buynow=true&Itemid=". JRequest::getInt('Itemid', 0));        		
        		return;
        	}
        }
        
        elseif($premium && !$item->id && $jbconfig['billing']->get('premium_posting_fee_enabled', 0)){
        	        
        	$account = getAccountByUserID($user->id);
        	if(!$account || (int)$account->premium_posts_balance<1){
        		$this->setRedirect("?option=$option&view=jajobs&layout=japremiumform&goto_buynow=true&Itemid=". JRequest::getInt('Itemid', 0));        		
        		return;
        	}
        	
        }
  		elseif($item->id && !$item->is_hotjob && $premium){
  			return JError::raiseWarning(JText::_("You don't have permission."));
  		}
        
        $step = JRequest::getVar('step', ''); 
        ($step == 'done') or JRequest::checkToken() or jexit( 'Invalid Token' );
        
        $Itemid = get_Itemid(array("option"=>JBCOMNAME, "view" => "jajobs", "layout"=>"jaview"));              
        $limited = JRequest::getVar('limited', 0);                        
        
        		
        $rc = $model->store();
                             
        if (($step=='done')&&(!$rc))
        	$rc=true;
        if($rc){
            if($step != 'done'){            	
                $item =& $model->getItem();               
                $alias = JFilterOutput::stringURLSafe($item->title);
                $this->setRedirect( JRoute::_('index.php?option='. JBCOMNAME .'&view=jajobs&layout=jaview&step=verify&is_newjob='.JRequest::getVar("is_newjob").'&cid[0]='.$item->id. '&alias='. $alias.'&Itemid='.$Itemid), JText::_('Job posting preview'));
            } else {
                if(getCurrentUserType() == JBEMPLOYER_USER){
                    require_once(JPATH_COMPONENT.DS."models".DS."jasendmail.php");
                }
            	// Send mail to Employer, Job has updated
                $msg = JText::_( 'Successfully updated job' );   
                $this->setRedirect( JRoute::_('index.php?option='. JBCOMNAME .'&view=jajobs&layout=myjobs'), $msg );
					
            }
        } else {
        	$is_hotjob = JRequest::getVar('is_hotjob',false);
//        	JError::raiseWarning(0, JText::_('There are some invalid data. Please check again'));
			$this->edit(true);
        }
        
	}		
    /**
    * Save selected jobs to shortlist
    * 
    */
    function starred(){
//        JRequest::checkToken() or jexit( 'Invalid Token' );
        
        $user = &JFactory::getUser();
        if($user->id){
            $task = JRequest::getVar('task', 'starred');
            $cid = JRequest::getVar('cid');
            $cid = $cid[0];
            $model =& $this->getModel('jashortlist' );
          
            $result = $model->starred($task);
            if ($result=='new')
            {
            	$this->setMessage(JText::sprintf(JText::_('SUCCESSFULLY ADDED TO MY FAVOURITE JOBS'), $n));
            	$this->setRedirect(JRoute::_('index.php?option='. JBCOMNAME .'&view=jajobs&layout=jajobseekerlist'));
            }
            else 
            {
            	$this->setMessage(JText::sprintf('This job is already saved', $n));
            	$this->setRedirect(JRoute::_('index.php?option='. JBCOMNAME .'&view=jajobs&layout=jaview&cid[]='.$cid)); 
            }   
        }
    }
    
    function sendfriend(){
        JRequest::setVar('sendfriend', true);
        $cid = JRequest::getVar('cid', array(), 'post', 'array');
        
        JArrayHelper::toInteger($cid);
        $Itemid = JRequest::getVar('Itemid');
        
        $model = & $this->getModel($this->get('fullname'));
        $result = $model->jobMailSendFriend($cid[0]);
        if ((JRequest::getVar('sendmyself')) and ($result))
        	$model->jobMailSendMe($cid[0]);
        if ($result)
        {
        	$this->setMessage(JText::_('Successfully recommended the job to your friend!'));
        	$this->setRedirect(JRoute::_('index.php?option='. JBCOMNAME .'&view='.$this->get('fullname').'&layout=jaview&cid[]='.$cid[0].'&Itemid='.$Itemid));    
        }
        else 
        {
        	JRequest::setVar('mail_postback',true);
        	JRequest::setVar('layout','jaview');
    		parent::display();
        }
    }


	function editList(){
    	$this->setRedirect(JRoute::_('index.php?option=com_jajobboard&view=jafieldlist&filter_table=ja_jobs')); 	
    }    
    
	function approved(){
		global  $option;
		
		if($this->getTask()=='approved') $status = 'Approved';
		else $status = 'Non-Approved';
		
		$model = $this->getModel('jajobs');
				
		if (!$model->approved($status)) {
			echo "<script> alert('".$model->getError(true)."'); window.history.go(-1); </script>\n";
			exit();
		}
		
		$this->setRedirect(JRoute::_("index.php?option=$option&view=jajobs"), "This job has $status !");
	}   

    function orderdown(){
    	global $option;
        // Check for request forgeries
        JRequest::checkToken() or jexit( 'Invalid Token' );
        
        $cid    = JRequest::getVar( 'cid', array(), 'post', 'array' );
        JArrayHelper::toInteger($cid);
        
        $task = JRequest::getVar('task', 'orderdown');

        if (isset($cid[0]) && $cid[0]) {
            $id = $cid[0];
        } else {
            $this->setRedirect( JRoute::_("index.php?option=$option&view=jajobs"), JText::_('No Items Selected') );
            return false;
        }

        $model =& $this->getModel( 'jajobs' );
        $movement = $task == 'orderdown' ? 1 : -1;

        if($model->orderItem($id, $movement)){
            $msg = $movement > 0 ? JText::_( 'Item Moved Down' ) : JText::_( 'Item Moved Up' );
        }
        
        $this->setRedirect( JRoute::_("index.php?option=$option&view=jajobs"), $msg );
    }
    
    /**
    * Save the item(s) order
    */
    function saveorder()
    {
    	global $option;
        // Check for request forgeries
        JRequest::checkToken() or jexit( 'Invalid Token' );
        
        $cid    = JRequest::getVar( 'cid', array(), 'post', 'array' );
        JArrayHelper::toInteger($cid);

        $model =& $this->getModel( 'jajobs' );
        if ($model->setOrderchu($cid)) {
            $msg = JText::_( 'New ordering saved' );
        } else {
            $msg = $model->getError();
        }
        $this->setRedirect( JRoute::_("index.php?option=$option&view=jajobs"), $msg );
    }
    function remove_attach()
    {
    	$model    =& $this->getModel( 'jajobs' );
    	$model->remove_attach();
         exit;
    }
	
    function multi_starred()
    {
    	$user = &JFactory::getUser();
    	if (!$user->id)
    	{
    		$uri		= JFactory::getURI();
			$return		= $uri->toString();
    		$this->setRedirect(JRoute::_("index.php?option=com_user&view=login&return=".base64_encode($return)),JText::_('You must log in to add favorite job(s)'));
        	return ;
    	}
    	$cid = JRequest::getVar('cid');
    	if (count($cid)>0)
    	{
	        if($user->id){
	        	if (JRequest::getVar('remove_starred'))
	        		$task = 'unstarred';
	        	else 
	        		$task = 'starred';
	            $model =& $this->getModel('jashortlist' );
	          
	            $result = $model->multi_starred($task);
	            if (!JRequest::getVar('remove_starred'))
	            {
		            if ($result)
		                $msg = JText::_('Successfully added to my favorite jobs');
			        else 
		            	$msg = JText::_('Unsuccessfully added to my favourite jobs');
		            $this->setRedirect(JRoute::_('index.php?option='. JBCOMNAME .'&view=jajobs&layout=jalist'),$msg);
	            }
	            else 
	            {
	            	if ($result)
		                $msg = JText::_('Successfully removed favorite jobs');
			        else 
		            	$msg = JText::_('Unsuccessfully removed favorite jobs');
		            
		            $this->setRedirect(JRoute::_('index.php?option='. JBCOMNAME .'&view=jajobs&layout=jajobseekerlist'),$msg);
	            }
	            
	        }
    	}
    	else 
    	{
    		if (!JRequest::getVar('remove_starred'))
    		{
	    		$msg = JText::_('Please make a selection from the list to save');
	    		$this->setRedirect(JRoute::_('index.php?option='. JBCOMNAME .'&view=jajobs&layout=jalist'),$msg);
    		}
    		else 
    		{
    			$msg = JText::_('Please make a selection from the list to remove favorite');
	    		$this->setRedirect(JRoute::_('index.php?option='. JBCOMNAME .'&view=jajobs&layout=jajobseekerlist'),$msg);
    		}
    	}
    }
    
    function multi_view()
    {
    	$cid = JRequest::getVar('cid');
//    	var_dump(JRequest::get('request'));exit;
    	if (count($cid)>0)
    	{
    		JRequest::setVar('layout','jaview');
    		$this->display();
    	}
    	else 
    	{
    		$msg = JText::_('Please make a selection from the list to view');
    		$this->setRedirect(JRoute::_('index.php?option='. JBCOMNAME .'&view=jajobs&layout=jalist&Itemid='.JRequest::getVar('Itemid')),$msg);
    	}
    }
    
    function multi_delete()
    {
    	$cid = JRequest::getVar('cid');
		
    	if (count($cid)>0)
    	{
    		global $option;
	 	        
			$cid = JRequest::getVar('cid',array(), 'post', 'array');
			$msg = '';
			$allow_del = true;
			$i=0;
			foreach ($cid as $id)
			{
				$applist = getItemByFieldName('ja_applications','job_id',$id);
				if (count($applist)>=1){
					$allow_del = false;
					$job = getItemByFieldName('ja_jobs','id',$id);
					$job = $job[0];
					JError::raiseWarning(1,  JText::_("You can not delete")." '$job->title' job. ".JText::_("Please delete all application of")." '$job->title'<br />&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp ");
					$this->setRedirect(JRoute::_('index.php?option='. JBCOMNAME .'&view=jajobs&layout=myjobs&Itemid='.JRequest::getVar('Itemid')));
					return;
				}
				$i++;
			}
			
			if( ! class_exists("JAJobBoardModelJAJobs") )
				require_once(JPATH_ADMINISTRATOR.DS."components".DS."com_jajobboard".DS."models".DS."jajobs.php");
	        
			$model = new JAJobBoardModelJAJobs();
	        
	        if(($n = $model->remove()) < 0){
	             JError::raiseWarning( 500, $row->getError() );
			}
			if ($n==1)
				JError::raiseWarning(1, JText::_('Successfully removed '.$i.' item!'));
			else 
				JError::raiseWarning(1, JText::_('Successfully removed '.$i.' items!'));
			
			$this->setRedirect(JRoute::_('index.php?option='. JBCOMNAME .'&view=jajobs&layout=myjobs&Itemid='.JRequest::getVar('Itemid')),$msg);
    		// $this->display();
    	}
    	else 
    	{
    		$msg = JText::_('Please make a selection from the list to delete');
    		$this->setRedirect(JRoute::_('index.php?option='. JBCOMNAME .'&view=jajobs&layout=jalist&Itemid='.JRequest::getVar('Itemid')),$msg);
    	}
    }
    
    function job_list_via_profiles()
    {
    	$cid = JRequest::getVar('cid');
    	if (count($cid)>0)
    	{
    		JRequest::setVar('layout','job_list_via_profiles');
    		$this->display();
    	}
    	else 
    	{
    		$msg = JText::_('Please make a selection from the list to view');
    		$this->setRedirect(JRoute::_('index.php?option='. JBCOMNAME .'&view=japrofiles&layout=jalist&Itemid='.JRequest::getVar('Itemid')),$msg);
    	}
    }
    
    
}
